package com.validators;

import java.lang.reflect.Field;
import java.util.List;

import javax.faces.context.FacesContext;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.apache.log4j.Logger;
import org.springframework.web.jsf.FacesContextUtils;

import com.common.BaseModel;
import com.dao.BaseModelDAO;
import com.view.BaseView;

public class UniqueFieldValidator implements
		ConstraintValidator<Unique, BaseView> {

	private BaseModelDAO<?> dao;
	private Class<?> entityClass;
	private String uniqueField;
	private String daoName;
	private Logger log = Logger.getLogger(UniqueFieldValidator.class);

	public void initialize(Unique unique) {
		entityClass = unique.entity();
		uniqueField = unique.property();
		daoName = unique.daoName();
	}

	@SuppressWarnings("unchecked")
	public boolean isValid(BaseView objeto, ConstraintValidatorContext cvContext) {

		List<Object> list = null;

		dao = (BaseModelDAO<BaseModel>) FacesContextUtils
				.getWebApplicationContext(FacesContext.getCurrentInstance())
				.getBean(daoName);

		// si estoy modificando no debe chequear si existe
		if (objeto.getId() == null) {
			Field field;
			Object value = null;
			try {
				field = objeto.getClass().getDeclaredField(uniqueField);
				field.setAccessible(true);
				value = field.get(objeto);
			} catch (Throwable e) {
				log.error(
						"Error al validar el objeto en el UniqueFieldValidator",
						e);
			}

			String query = String.format("from %s where %s = ? ",
					entityClass.getName(), uniqueField);
			list = (List<Object>) dao.find(query, value.toString());
		}

		return list == null || list.size() == 0;
	}
}